package org.dromara.event.service.impl;

import com.alibaba.fastjson.JSON;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.event.domain.ChatGroup;
import org.dromara.event.mapper.ChatGroupMapper;
import org.dromara.system.domain.SysOss;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysOssMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.event.domain.bo.ChatMessageBo;
import org.dromara.event.domain.vo.ChatMessageVo;
import org.dromara.event.domain.ChatMessage;
import org.dromara.event.mapper.ChatMessageMapper;
import org.dromara.event.service.IChatMessageService;

import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 聊天消息（按群组分区存储）Service业务层处理
 *
 * @author 吴俊杰
 * @date 2025-04-24
 */
@RequiredArgsConstructor
@Service
public class ChatMessageServiceImpl implements IChatMessageService {

    private final ChatMessageMapper baseMapper;

    private final ChatGroupMapper chatGroupMapper;

    private final SysUserMapper sysUserMapper;

    private final SysOssMapper sysOssMapper;

    private final ScheduledExecutorService scheduledExecutorService;

    /**
     * 查询聊天消息（按群组分区存储）
     *
     * @param messageId 主键
     * @return 聊天消息（按群组分区存储）
     */
    @Override
    public ChatMessageVo queryById(Long messageId){
        return baseMapper.selectVoById(messageId);
    }

    /**
     * 分页查询聊天消息（按群组分区存储）列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 聊天消息（按群组分区存储）分页列表
     */
    @Override
    public TableDataInfo<ChatMessageVo> queryPageList(ChatMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ChatMessage> lqw = buildQueryWrapper(bo);
        Page<ChatMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(r -> r.setIsSelf(r.getSenderId().equals(LoginHelper.getUserId()) ? "1" : "0"));
        //设置用户名和用户头像
        result.getRecords().forEach(r -> r.setUsrAvatar(sysOssMapper.selectVoById(sysUserMapper.selectById(r.getSenderId()).getAvatar()).getUrl()));
        result.getRecords().forEach(r -> r.setUsername(sysUserMapper.selectById(r.getSenderId()).getUserName()));
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的聊天消息（按群组分区存储）列表
     *
     * @param bo 查询条件
     * @return 聊天消息（按群组分区存储）列表
     */
    @Override
    public List<ChatMessageVo> queryList(ChatMessageBo bo) {
        LambdaQueryWrapper<ChatMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChatMessage> buildQueryWrapper(ChatMessageBo bo) {
        LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ChatMessage::getMessageId);
        lqw.eq(bo.getGroupId() != null, ChatMessage::getGroupId, bo.getGroupId());
        lqw.eq(bo.getSenderId() != null, ChatMessage::getSenderId, bo.getSenderId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), ChatMessage::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageType()), ChatMessage::getMessageType, bo.getMessageType());
        lqw.eq(bo.getSendTime() != null, ChatMessage::getSendTime, bo.getSendTime());
        return lqw;
    }

    /**
     * 新增聊天消息（按群组分区存储）
     *
     * @param bo 聊天消息（按群组分区存储）
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ChatMessageBo bo) {
        ChatMessage add = MapstructUtils.convert(bo, ChatMessage.class);
        add.setSenderId(LoginHelper.getUserId());
        add.setSendTime(new Date());
        ChatGroup now = chatGroupMapper.selectById(add.getGroupId());
        List<Long> existMembers = StringUtils.isBlank(now.getMemberIds()) ?
            new ArrayList<>() :
            JSON.parseArray(now.getMemberIds(), Long.class);
        existMembers.forEach(
            memberId -> {
                if (memberId.equals(LoginHelper.getUserId())){
//                    scheduledExecutorService.schedule(() -> {
//                        SseMessageDto dto = new SseMessageDto();
//                        dto.setMessage(bo.getContent());
//                        dto.setGroupId(bo.getGroupId());
//                        dto.setUserIds(List.of(LoginHelper.getUserId()));
//                        dto.setIsSelf("1");
//                        SseMessageUtils.publishMessage(dto);
//                    }, 5, TimeUnit.SECONDS);
                }else {
                    scheduledExecutorService.schedule(() -> {
                        SseMessageDto dto = new SseMessageDto();
                        dto.setMessage("["+add.getGroupId()+"]"+"["+bo.getContent()+"]"+"["+"0"+"]"+"["+sysOssMapper.selectVoById(sysUserMapper.selectById(add.getSenderId()).getAvatar()).getUrl()+"]"+"["+sysUserMapper.selectById(add.getSenderId()).getUserName()+"]"+"["+new Date()+"]");
                        dto.setGroupId(bo.getGroupId());
                        dto.setUserIds(List.of(memberId));
                        dto.setIsSelf("0");
                        SseMessageUtils.publishMessage(dto);
                    }, 5, TimeUnit.SECONDS);

                }
            }
        );
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMessageId(add.getMessageId());
        }
        return flag;
    }

    /**
     * 修改聊天消息（按群组分区存储）
     *
     * @param bo 聊天消息（按群组分区存储）
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ChatMessageBo bo) {
        ChatMessage update = MapstructUtils.convert(bo, ChatMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChatMessage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除聊天消息（按群组分区存储）信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
